﻿using ServerSide.EFCoreContext;
using ServerSide.Model;

namespace ServerSide.utils
{
    public class TokenUtil
    {
        //设置校验半个小时校验间隔
        double interval = 0.5;
        //传入相应的dbcontext
        private readonly MyDBContext _myDBContext;
        public TokenUtil(MyDBContext myDBContext)
        {
            _myDBContext = myDBContext;
        }

        //模拟生成随机token
        public string GenerateToken()
        {
            Random random = new Random();
            string token = random.Next(1000000, 9999999).ToString();
            return token;
        }
        /// <summary>
        /// 存入Token校验有效期和Token
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public Boolean SetTokenValidityTime(User user, string token)
        {
            DateTime time = DateTime.Now.AddHours(interval);
            user.Token = token;
            user.VaildTime = time.ToString();
            try
            {
                _myDBContext.User.Update(user);
                _myDBContext.SaveChanges();
            }
            catch (Exception)
            {
              return false;
            }
            return true;
        }
    }
}
